﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.ProductForm;
using BW.Mes.WinForms.BasicData;

namespace BW.Mes.WinForms.BasicData
{
    public partial class ProductForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _productApiBaseUrl = "http://120.26.197.100:8022";
        private DevExpress.XtraEditors.SimpleButton btnEdit;
        public ProductForm()
        {
            InitializeComponent();
            //初始化httpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            // 窗体加载时获取数据
            pagerControl1.PageChanged += async (s, e2) =>
            {
                await LoadProductData(pagerControl1.PageIndex, pagerControl1.PageSize);
            };
            this.Load += async (s, e) =>
            {
                await LoadProductData(1, pagerControl1.PageSize);
            };
            this.simpleButton1.Click += simpleButton1_Click;
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
            // 新增：修改按钮
            btnEdit = new DevExpress.XtraEditors.SimpleButton();
            btnEdit.Text = "修改";
            btnEdit.Size = new System.Drawing.Size(107, 36);
            btnEdit.Location = new System.Drawing.Point(400, 88);
            // 设置按钮背景色和字体色
            btnEdit.Appearance.BackColor = ColorTranslator.FromHtml("#c6f1ff");
            btnEdit.Appearance.Options.UseBackColor = true;
            btnEdit.Appearance.ForeColor = Color.Black;
            btnEdit.Appearance.Options.UseForeColor = true;
            this.panelControl1.Controls.Add(btnEdit);
            // 启用多选复选框列
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

            // 斑马纹美化（蓝色风格，取自用户图片）
            gridView1.Appearance.EvenRow.BackColor = ColorTranslator.FromHtml("#c6f1ff");
            gridView1.Appearance.EvenRow.Options.UseBackColor = true;
            gridView1.Appearance.OddRow.BackColor = ColorTranslator.FromHtml("#e6faff");
            gridView1.Appearance.OddRow.Options.UseBackColor = true;
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            // 表头同色
            gridView1.Appearance.HeaderPanel.BackColor = ColorTranslator.FromHtml("#c6f1ff");
            gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;
            // 选中行不覆盖背景色
            gridView1.Appearance.FocusedRow.BackColor = Color.Transparent;
            gridView1.Appearance.FocusedRow.Options.UseBackColor = false;
            gridView1.Appearance.HideSelectionRow.BackColor = Color.Transparent;
            gridView1.Appearance.HideSelectionRow.Options.UseBackColor = false;
            // 禁用皮肤影响
            gridView1.Appearance.Row.BackColor = Color.Empty;
            gridView1.Appearance.Row.Options.UseBackColor = false;
        }

        private async void ProductForm_Load(object sender, EventArgs e)
        {
            
            await LoadProductData(1, pagerControl1.PageSize);
        }
        // 加载仓库数据
        private async Task LoadProductData(int pageIndex, int pageSize)
        {
            try
            {
                string url = $"T2/Product/GetProduct?PageIndex={pageIndex}&PageSize={pageSize}";
                List<ProductModel> data = null;
                int totalCount = pagerControl1.TotalCount;
                var result = await GetApiDataAsync<ProductPageResult>(url);
                if (result == null)
                {
                    data = await GetApiDataAsync<List<ProductModel>>(url);
                }
                else
                {
                    data = result?.pageDatas ?? new List<ProductModel>();
                    totalCount = result?.totalCount ?? 0;
                }
                gridControl1.DataSource = data;
                pagerControl1.TotalCount = totalCount;
                pagerControl1.PageIndex = pageIndex;
                pagerControl1.PageSize = pageSize;
                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                gridView1.RefreshData();
                if (gridView1.Columns["Id"] != null)
                    gridView1.Columns["Id"].Visible = false;
                if (gridView1.Columns["MaterialId"] != null)
                    gridView1.Columns["MaterialId"].Visible = false;
                EnsureSerialNumberColumn();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
            }
        }
        /// <summary>
        /// 产品
        /// </summary>
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_productApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
        // 提交数据到API
        public async Task<bool> PostApiDataAsync<T>(string endpoint, T data)
        {
            try
            {
                string jsonData = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync($"{_productApiBaseUrl}/{endpoint}", content);
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"提交数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        /// <summary>
        /// 产品物料
        /// </summary>
        public class ProductModel
        {
            public long Id { get; set; } // 主键
            public long MaterialId { get; set; } // 物料群组Id
            /// <summary>
            /// 产品编号
            /// </summary>
            [DisplayName("编号")]
            public string ProductCode { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            [DisplayName("产品名称")]
            public string ProductName { get; set; }
            /// <summary>
            /// 规格型号
            /// </summary>
            [DisplayName("规格型号")]
            public string Specification { get; set; }
            /// <summary>
            /// 单位
            /// </summary>
             [DisplayName("单位")]
            public string Unit { get; set; }
            // <summary>
            /// 预警值
            /// </summary>
             [DisplayName("预警值")]
            public int Warning { get; set; }
            /// <summary>
            /// 群组类型
            /// </summary>
            [DisplayName("群组类型")]
            public string MaterialType { get; set; }
            [DisplayName("群组")]
            public string MaterialName { get; set; }
            /// <summary>
            /// 产品描述
            /// </summary>
            [DisplayName("产品描述")]
            public string ProductMsg { get; set; }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            LoadProductData(1, pagerControl1.PageSize);
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            var addForm = new AddProductForm();
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                await LoadProductData(1, pagerControl1.PageSize);
            }
        }
      
        private async Task<(bool, string)> DeleteProduct(long id)
        {
            try
            {
                var response = await _httpClient.PutAsync($"{_productApiBaseUrl}/T2/Product/DeleteProduct?id={id}", null);
                var responseContent = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                    if (apiResult != null && apiResult.code == 200)
                    {
                        return (true, null);
                    }
                    else
                    {
                        string errorMessage = apiResult?.message ?? "删除失败，但未返回具体错误信息。";
                        return (false, errorMessage);
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误: {response.StatusCode}";
                    try
                    {
                        var errorResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (errorResult != null && !string.IsNullOrEmpty(errorResult.message))
                        {
                            errorMessage = errorResult.message;
                        }
                    }
                    catch { }
                    return (false, errorMessage);
                }
            }
            catch (Exception ex)
            {
                return (false, $"删除时发生异常: {ex.Message}");
            }
        }

        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 个产品吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            int successCount = 0;
            int failureCount = 0;
            string firstError = null;

            foreach (var rowHandle in selectedRows)
            {
                var product = gridView1.GetRow(rowHandle) as ProductModel;
                if (product != null)
                {
                    var (success, errorMsg) = await DeleteProduct(product.Id);
                    if (success)
                    {
                        successCount++;
                    }
                    else
                    {
                        failureCount++;
                        if (firstError == null)
                            firstError = errorMsg;
                    }
                }
            }

            await LoadProductData(pagerControl1.PageIndex, pagerControl1.PageSize);

            if (successCount > 0 && failureCount == 0)
            {
                XtraMessageBox.Show($"成功删除 {successCount} 个产品。", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (successCount > 0 && failureCount > 0)
            {
                XtraMessageBox.Show($"成功删除 {successCount} 个产品，{failureCount} 个产品删除失败。\n第一个失败原因：{firstError}", "操作完成", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (failureCount > 0)
            {
                XtraMessageBox.Show(firstError, "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            LoadProductData(1, pagerControl1.PageSize);
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadProductData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }
        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }
        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        public class ProductPageResult
        {
            public int totalCount { get; set; }
            public List<ProductModel> pageDatas { get; set; }
            public string message { get; set; }
            public object data { get; set; }
            public int code { get; set; }
        }

        private void simpleButton2_Click_1(object sender, EventArgs e)
        {
            var data = gridControl1.DataSource as IEnumerable<ProductModel>;
            if (data == null) { XtraMessageBox.Show("无数据！"); return; }
            // 只允许选中一行进行修改
            var selectedRowHandle = gridView1.FocusedRowHandle;
            if (selectedRowHandle < 0)
            {
                XtraMessageBox.Show("请选中一条要修改的数据！");
                return;
            }
            var row = gridView1.GetRow(selectedRowHandle) as ProductModel;
            if (row == null)
            {
                XtraMessageBox.Show("未获取到产品信息！");
                return;
            }
            var updateForm = new AddProductForm(row);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                 LoadProductData(pagerControl1.PageIndex, pagerControl1.PageSize);
            }
        }
    }
}